import Shop from '../model/shop'
import Order from '../model/orders'
import Reason from '../model/refund'
import { create, saveTo1688Data } from '../api/token'
import aesDecrypt from '../utils/aesDecrypt'
import { rightsInfo } from '../api/token'
import moment from 'moment'
import { aiSendShopSorce } from '../config/index'
import axios from 'axios'
import redis from '../dbHelper/redis'
// import fs from 'fs'

const JSONbig = require('json-bigint')({ storeAsString: true })

class TokenController {
	static async create(ctx) {
		// ctx.redirect('/')
		// ctx.body = '123'

		ctx.query.code = ctx.query.code || ctx.query.authCode
		if (!ctx.query.code) {
			ctx.redirect('/?msg=缺少code')
			return
		}

		const res = await create({
			grant_type: 'authorization_code',
			code: ctx.query.code,
		})
		if (res.code == 10000) {
			// console.log('res授权成功', res)
			// saveTo1688Data(res)
			const shopData = await Shop.findOne({ shop_id: res.data.shop_id })

			if (shopData) {
				Object.keys(res.data).forEach(item => {
					shopData[item] = res.data[item]
				})
				// shopData.access_token = res.data.access_token
				shopData.access_token_update_time = new Date()
				shopData.action_type = 2
				await shopData.save()
			} else {
				await new Shop({
					shop_id: res.data.shop_id,
					// access_token: res.data.access_token,
					...res.data,
					action_type: 2,
					access_token_update_time: new Date(),
				}).save()
			}
			// 调用授权详情

			// 查询权益详情 更新保存权益信息
			const rightsInfoData = await rightsInfo({
				access_token: res.data.access_token,
			})
			// console.log('目前的权益：：：', rightsInfoData)
			if (rightsInfoData.code == 10000) {
				if (moment(rightsInfoData.data.expire_time).isAfter(moment())) {
					if (shopData) {
						shopData.isBuy = rightsInfoData.data.rights_type ? 1 : 2
						shopData.service_end_time = new Date(rightsInfoData.data.expire_time).getTime() / 1000
						await shopData.save()
					}
				}
			}
			// console.log('res', res)
			// URLSearchParams(`http://localhost:5666/getgoods/1688-strict-selection?binddy=${JSON.stringify(res)}`)
			// ctx.redirect(`http://localhost:5666/bind-dly-dy?binddy=${JSON.stringify(res)}`)


			// ctx.redirect(`https://dly1688.lntelliai.com/bind-dly-dy?binddy=${JSON.stringify(res)}`)
			ctx.redirect(`${process.env.BUY_APP_CB_URL}&binddy=${JSON.stringify(res)}`)

			return
		}

		ctx.redirect('/?msg=' + res.msg + res.sub_msg)
		// ctx.body = res.msg + res.sub_msg
	}
	static async callbackShopbuy(ctx) {
		// createTime时间大于15日
		// const getData = await Shop.find({
		//     createTime: {
		//         $gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 15),
		//     }
		// })
		// const setData = await Shop.find({
		// 	createTime: {
		// 	    $gte: new Date('2024-04-14').getTime(),
		// 	}
		// })
		// console.log('setData', setData)
		// setData.forEach(async (item) => {
		//     item.createDate = moment(item.createTime).format('YYYY-MM-DD')
		// 	item.save()
		// })
		// // setData.for
		// return
		// process.env.APP_SECRET
		const appSecret = process.env.APP_SECRET // 'a5c5a2dc-31ca-4a7a-b743-e862d96082bd' //  process.env.APP_SECRET
		// const appSecret = process.env.APP_SECRET
		const msgSecret = ctx.request.body
		axios.post('https://dly1688.lntelliai.com/weitong/company/openServerDly', { param_json: msgSecret })
		// console.log('msgSecret加密信息', msgSecret)
		// return
		// fs.appendFile('example.txt', `${msgSecret}\n\n\n*****-----*********`, (err) => {
		// 	console.log('追加结果')
		// })

		// console.log('目前的权益：：：', rightsInfoData)

		try {
			// 保存数据到数据库
			const DataJson = JSONbig.parse(aesDecrypt(msgSecret, appSecret))

			// fs.appendFile('example.txt', `${JSON.stringify(DataJson)}\n\n\n*****2222222*********`, (err) => {
			// 	console.log('追加结果')
			// })
			const buyMsg = JSONbig.parse(DataJson.msg)
			const getShopDtat = await Shop.findOne({ shop_id: buyMsg.shop_id || buyMsg.ShopId || buyMsg.order_info.shop_id })
			// console.log('getShopDtat', getShopDtat)
			// const rightsInfoData = await rightsInfo({
			// 	access_token: getShopDtat.access_token,
			// })
			// if (rightsInfoData.code == 10000) {
			// 	if (getShopDtat) {

			// 		getShopDtat.isBuy = rightsInfoData.data.rights_type ? 1 : 2
			// 		getShopDtat.service_end_time = new Date(rightsInfoData.data.expire_time).getTime() / 1000
			// 		await getShopDtat.save()
			// 	} else {
			// 		await new Shop({
			// 			shop_id: buyMsg.shop_id || buyMsg.ShopId || buyMsg.order_info.shop_id,
			// 			isBuy: rightsInfoData.data.rights_type ? 1 : 2,
			// 			service_end_time: new Date(rightsInfoData.data.expire_time).getTime() / 1000,
			// 		}).save()
			// 	}
			// }

			// ctx.body = {
			// 	code: 0,
			// 	msg: 'ok',
			// }
			// return
			// console.log('getShopDtat', getShopDtat)
			// console.log('回调信息', buyMsg)
			// return
			if (DataJson.msg_type === 1) {
				// 订购信息
				const orderBuyData = {
					app_id: buyMsg.app_id,
					proxyId: getShopDtat && getShopDtat.proxyId || null,
					proxyLinkId: getShopDtat && getShopDtat.proxyLinkId || null,
					channelCode: getShopDtat && getShopDtat.channelCode || null,
					...buyMsg.order_info,
					isGive: 1
				}
				// console.log('buyMsg', buyMsg)
				// console.log('orderBuyData00', orderBuyData)
				// 如果数据库中没有order_id 不存在则存入数据库
				const getorderData = await Order.findOne({ order_id: orderBuyData.order_id + '' })
				// console.log('getorderData', getorderData)
				if (!getorderData) {
					await Order({
						...orderBuyData,
					}).save()
				}
				// console.log('getShopDtat', getShopDtat)
				// console.log('orderBuyData', orderBuyData)
				// return
				// console.log('getShopDtat', getShopDtat)

				if (getShopDtat) {
					getShopDtat.service_start_time = orderBuyData.service_start_time
					getShopDtat.service_end_time = orderBuyData.service_end_time
					getShopDtat.isBuy = orderBuyData.pay_type === 7 ? 2 : 1
					await getShopDtat.save()
				} else {
					await new Shop({
						shop_id: orderBuyData.shop_id,
						service_start_time: orderBuyData.service_start_time,
						service_end_time: orderBuyData.service_end_time,
						isBuy: orderBuyData.pay_type === 7 ? 2 : 1
					}).save()
				}

				const giveData = aiSendShopSorce.find((item) => item.spec_value == orderBuyData.push_sku_info.spec_value).chr.find((item) => item.title == orderBuyData.push_sku_info.title)
				if (giveData) {
					// 给用户送积分
					await Shop.updateOne({ shop_id }, {
						$inc: { aiRemainScore: giveData.give_num }
					})
					// getShopOrderData.isGive = 1
					// getShopOrderData.save()
				}
				let shopData = await Shop.findOne({ shop_id: buyMsg.shop_id })
				await redis.set(`shopid_${buyMsg.shop_id}`, JSON.stringify(shopData))
				await redis.expire(`shopid_${buyMsg.shop_id}`, 60 * 2)
				ctx.body = {
					code: 0,
					msg: 'ok',
				}
				return
			}
			if (DataJson.msg_type === 2) {
				// 授权相关
				if (getShopDtat) {
					getShopDtat.action_type = buyMsg.action_type
					await getShopDtat.save()
				} else {
					await new Shop({
						shop_id: buyMsg.shop_id,
						action_type: buyMsg.action_type
					}).save()
				}
				let shopData = await Shop.findOne({ shop_id: buyMsg.shop_id })
				await redis.set(`shopid_${buyMsg.shop_id}`, JSON.stringify(shopData))
				await redis.expire(`shopid_${buyMsg.shop_id}`, 60 * 2)
				ctx.body = {
					code: 0,
					msg: 'ok',
				}
				return
			}
			if (DataJson.msg_type === 3) {
				// 申请退款信息
				// 保存退款信息
				const getReData = Reason.findOne({
					AftersaleId: buyMsg.AftersaleId
				})
				if (!getReData) {
					const ReasonData = new Reason({
						app_id: process.env.APP_KEY,
						...buyMsg,
						refundStatusIs: 0, // 0 已申请未退款
					})
					await ReasonData.save()
				}
				let shopData = await Shop.findOne({ shop_id: buyMsg.shop_id })
				await redis.set(`shopid_${buyMsg.shop_id}`, JSON.stringify(shopData))
				await redis.expire(`shopid_${buyMsg.shop_id}`, 60 * 2)
				ctx.body = {
					code: 0,
					msg: 'ok',
				}
				return
			}
			if (DataJson.msg_type === 4) {
				const refundData = await Reason.findOne({
					OrderId: buyMsg.order_id || buyMsg.OrderId
				})
				if (refundData) {
					refundData.RefundStatus = buyMsg.RefundStatus
					refundData.refundStatusIs = 1
					await refundData.save()
				} else {
					await new Reason({
						app_id: process.env.APP_KEY,
						...buyMsg,
						refundStatusIs: 1, // 0 已申请未退款
					}).save()
				}
				// 申请退款 退款成功
				let orderData = await Order.findOne({
					order_id: buyMsg.order_id || buyMsg.OrderId
				})
				if (orderData) {
					orderData.isRefund = 1
					await orderData.save()
				} else {
					orderData = await new Order({
						order_id: buyMsg.order_id || buyMsg.OrderId,
						isRefund: 1
					}).save()
				}
				const giveData = aiSendShopSorce.find((item) => item.spec_value == orderData.push_sku_info.spec_value).chr.find((item) => item.title == orderData.push_sku_info.title)
				// 减去shop表中的积分
				// await Shop.updateOne({ shop_id: orderData.shop_id }, {
				//     // 减去aiRemainScore字段 最小为0
				// 	$inc: { aiRemainScore: -giveData.give_num }
				// })
				if (getShopDtat) {
					getShopDtat.aiRemainScore = getShopDtat.aiRemainScore - giveData.give_num > 0 ? getShopDtat.aiRemainScore - giveData.give_num : 0
					await getShopDtat.save()
				}
				// 这里匹配退款的项目 清空对应积分


				// 查找最后一笔未退款订单，重新赋值时间
				// console.log('buyMsg', buyMsg)
				const getShopOrderData = await Order.find({
					shop_id: buyMsg.shop_id || buyMsg.ShopId,
					isRefund: 0,
				})
					.sort({ createTime: -1 })
					.limit(1)
					.exec()
				// console.log('getShopOrderData', getShopOrderData)
				// return
				if (getShopOrderData) {
					// console.log('getShopOrderData', getShopOrderData)
					const orderBuyData = getShopOrderData[0]
					const buyNowEndTime = moment().isBefore(
						orderBuyData.service_end_time * 1000
					) // t 未过期 f 已经过期
					// console.log('buyNowEndTime', buyNowEndTime)
					// return
					await Shop.findOneAndUpdate(
						{ shop_id: orderBuyData.shop_id },
						{
							$set: {
								service_start_time:
									orderBuyData.service_start_time,
								service_end_time: orderBuyData.service_end_time,
								isBuy: buyNowEndTime ? 1 : 3,
							},
						},
						{ new: true, upsert: true }
					)
				} else {
					await Shop.findOneAndUpdate(
						{ shop_id: buyMsg.ShopId || buyMsg.shop_id },
						{
							$set: {
								service_start_time: 0,
								service_end_time: 0,
								isBuy: 4,
							},
						},
						{ new: true, upsert: true }
					)
				}
				let shopData = await Shop.findOne({ shop_id: buyMsg.shop_id })
				await redis.set(`shopid_${buyMsg.shop_id}`, JSON.stringify(shopData))
				await redis.expire(`shopid_${buyMsg.shop_id}`, 60 * 2)
				// console.log('目前的权益：：2222：', rightsInfoData)
				// if (rightsInfoData.code == 10000) {
				// 	await Shop.findOneAndUpdate(
				// 		{ shop_id: buyMsg.ShopId || buyMsg.shop_id },
				// 		{
				// 			$set: {
				// 				isBuy: rightsInfoData.data.rights_type ? 1 : 2,
				// 				service_end_time:
				// 					new Date(
				// 						rightsInfoData.data.expire_time
				// 					).getTime() / 1000,
				// 			},
				// 		},
				// 		{ new: true, upsert: true }
				// 	)
				// } else {
				// 	await Shop.findOneAndUpdate(
				// 		{ shop_id: buyMsg.ShopId || buyMsg.shop_id },
				// 		{
				// 			$set: {
				// 				service_start_time: 0,
				// 				service_end_time: 0,
				// 				isBuy: 4,
				// 			},
				// 		},
				// 		{ new: true, upsert: true }
				// 	)
				// }
				ctx.body = {
					code: 0,
					msg: 'ok',
				}
				return
			}
			ctx.body = {
				code: -1,
				msg: `msg_type==${DataJson.msg_type}未解析`,
			}
		} catch (error) {
			console.log('error', error)
			ctx.body = 0
			return
		}

		ctx.body = 132465
	}
}

export default TokenController
